package com.jamaskii.thread;

import java.util.ArrayList;

public class TaskGroup {
    final public ArrayList<Task> tasks=new ArrayList<>();
    private int ants;
    private Thread mainLoop;

    public TaskGroup(){

    }

    public void start(final int threads,final Runnable onComplete){
        mainLoop=new Thread(new Runnable() {
            @Override
            public void run() {
                int i=0;
                while (tasks.size()!=getDoneTask().size()){
                    if(getTask(Task.STATUE_LIVE).size()<threads && i<tasks.size()){
                        final int index=i;
                        i++;
                        Thread subThread=new Thread(new Runnable() {
                            @Override
                            public void run() {
                                tasks.get(index).start();
                            }
                        });
                        subThread.start();
                    }
                }
                onComplete.run();
            }
        });
        mainLoop.start();
    }

    public ArrayList<Task> getTask(int statue){
        ArrayList<Task> targets=new ArrayList<>();
        for (Task task:tasks
        ) {
            if(task.statue==statue){
                targets.add(task);
            }
        }
        return targets;
    }

    public ArrayList<Task> getDoneTask(){
        ArrayList<Task> targets=new ArrayList<>();
        for (Task task:tasks
        ) {
            if(task.done){
                targets.add(task);
            }
        }
        return targets;
    }

}
